package com.example.democlient.lambda;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8中内置的四大核心函数式接口
 *
 * Consumer<T>: 消费型接口
 *             void accept(T t)
 *
 *Supplier<T> : 供给型接口
 *            T get();
 *
 * Function<T,R> :函数型接口 T 参数，R 返回值
 *            R apply（T t）
 *
 * Predicate<T> : 断言型接口(做判断的)
 *             boolean test(T t)
 *
 */
public class Lambda3 {

    //Predicate<T> : 断言型接口(做判断的)

    @Test
    public void test4(){
        List<String> list = Arrays.asList("hello","hahah","www","ok");
        List<String> stringList = filterStr(list, (x) -> x.length() > 3);
        for(String s:stringList){
            System.out.println(s);
        }
    }

    //需求：将满足条件的字符串放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pr){
        List<String> stringList = new ArrayList<>();
        for(String s:list){
            if(pr.test(s)){
                stringList.add(s);
            }
        }
        return stringList;
    }




    //Function<T,R> :函数型接口 T 参数，R 返回值

    @Test
    public void test3(){
        String newStr = strHandler("   uuu  ",(s)->s.trim());
        System.out.println(newStr);
    }

    //需求：用于处理字符串
    public String strHandler(String str, Function<String,String> fun){
         return fun.apply(str);
    }



    //Supplier<T> : 供给型接口

    @Test
    public void  test2(){
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        for(Integer i:numList){
            System.out.println(i);
        }

    }
    //需求：产生指定个数的整数，并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> numList = new ArrayList<>();
        for(int i=0;i<num;i++){
            numList.add(sup.get());
        }
        return numList;

    }

    //Consumer<T>: 消费型接口
    @Test
    public void test1(){

        happy(1000,(m)-> System.out.println("消费去了，消费了"+m));
    }

    public void happy(double money, Consumer<Double> con){

        con.accept(money);
    }


}
